<?php
class FrontController {

	public static function main() {

		session_start();
    	$config = Config::singleton();
    	$controller = self::getController();
    	$action = self::getAction();
    	$controller_name = ucfirst($controller).'Controller';
    	$controller_file = $config->get('controllers_path').$controller_name.'.php';
    	try{
	  		if(!file_exists($controller_file)){
	    		throw new Exception('Error: El archivo del controlador invocado no existe.');
	  		}
      		if(!class_exists($controller_name)){
	    		throw new Exception('Error: La clase del controlador invocado no existe.');
	  		}
      		$objController = new $controller_name();
      		$objController->$action();
    	}
    	catch(Exception $e){
      		echo $e->getMessage();
    	}
  	}

	private function getController(){
		if(!empty($_GET['controller'])){
      		$controller = $_GET['controller'];
    	}
    	else{
      		if(!empty($_POST['controller'])){
        		$controller = $_POST['controller'];
      		}
      		else{
        		$controller = 'index';
      		}
    	}
    	return $controller;
	}

	private function getAction(){
		if(!empty($_GET['action'])){
      		$action = $_GET['action'];
    	}
    	else{
      		if(!empty($_POST['action'])){
        		$action = $_POST['action'];
      		}
      		else{
        		$action = 'index';
      		}
    	}
    	$action_parts = split('_', $action);
    	if(count($action_parts) > 1){
    		$action = $action_parts[0];
    		for($i=1; $i < count($action_parts); $i++){
    			$action .= ucfirst($action_parts[$i]);
    		}
    	}
    	return $action;
	}

}
?>